package com.campus.counseling.controller;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;

@RestController
@RequestMapping("/api/file")
@RequiredArgsConstructor
@Slf4j
public class FileAccessController {

    @Value("${spring.file.upload.path}")
    private String uploadPath;

    @GetMapping("/avatars/{filename}")
    public ResponseEntity<Resource> getAvatar(@PathVariable String filename) {
        // 构建文件的完整路径
        File file = new File(new File(uploadPath, "avatars"), filename).getAbsoluteFile();
        log.info("访问头像文件路径: {}", file.getAbsolutePath());
        
        // 检查文件是否存在
        if (!file.exists()) {
            log.error("头像文件不存在: {}", file.getAbsolutePath());
            return ResponseEntity.notFound().build();
        }

        try {
            // 获取文件的 MIME 类型
            String contentType = Files.probeContentType(file.toPath());
            if (contentType == null) {
                contentType = MediaType.APPLICATION_OCTET_STREAM_VALUE;
            }
            log.info("头像文件类型: {}", contentType);

            // 返回文件资源
            return ResponseEntity.ok()
                .contentType(MediaType.parseMediaType(contentType))
                .body(new FileSystemResource(file));
        } catch (IOException e) {
            log.error("获取头像文件类型失败", e);
            return ResponseEntity.internalServerError().build();
        }
    }

    @GetMapping("/certificates/{filename}")
    public ResponseEntity<Resource> getCertificate(@PathVariable String filename) {
        log.info("开始访问证书文件: {}", filename);
        
        try {
            // 构建文件的完整路径
            Path certificatesPath = new File(uploadPath, "certificates").toPath();
            Path filePath = certificatesPath.resolve(filename).toAbsolutePath().normalize();
            File file = filePath.toFile();
            
            log.info("证书文件完整路径: {}", file.getAbsolutePath());
            
            // 安全检查：确保请求的文件确实在certificates目录下
            if (!file.getAbsolutePath().startsWith(certificatesPath.toAbsolutePath().toString())) {
                log.error("非法的文件访问请求，文件路径: {}", file.getAbsolutePath());
                return ResponseEntity.badRequest().build();
            }
            
            // 检查文件是否存在
            if (!file.exists()) {
                log.error("证书文件不存在: {}", file.getAbsolutePath());
                return ResponseEntity.notFound().build();
            }

            // 检查文件是否可读
            if (!file.canRead()) {
                log.error("证书文件无法读取: {}", file.getAbsolutePath());
                return ResponseEntity.status(403).build();
            }

            // 获取文件的 MIME 类型
            String contentType = Files.probeContentType(file.toPath());
            if (contentType == null) {
                contentType = MediaType.APPLICATION_OCTET_STREAM_VALUE;
            }
            log.info("证书文件类型: {}", contentType);

            // 设置响应头
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.parseMediaType(contentType));
            // 添加缓存控制
            headers.setCacheControl("no-cache, no-store, must-revalidate");
            headers.setPragma("no-cache");
            headers.setExpires(0);

            // 返回文件资源
            return ResponseEntity.ok()
                .headers(headers)
                .body(new FileSystemResource(file));
        } catch (Exception e) {
            log.error("访问证书文件失败: {}, 错误: {}", filename, e.getMessage(), e);
            return ResponseEntity.internalServerError().build();
        }
    }
} 